package com.qf.openapi.web.master.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

@WebFilter("/*")
@Slf4j
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("======================MyFilter初始化===================");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Enumeration<String> headerNames = ((HttpServletRequest) request).getHeaderNames();

        String requestURI = ((HttpServletRequest) request).getRequestURI();
        log.debug("===>url={}",requestURI);

        //把请求中的参数信息打印出来
        Map<String, String[]> parameterMap = request.getParameterMap();
        ArrayList<HashMap<String, List<String>>> params = new ArrayList<>();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            String paramName = entry.getKey();
            String[] paramValue = entry.getValue();
            List<String> paramlist  = Arrays.asList(paramValue);
            HashMap<String, List<String>> map = new HashMap<>();
            map.put(paramName,paramlist);
            params.add(map);
        }

        log.debug("请求参数是params={}",params);

        //请求头信息打印
        HashMap<String, String> headerMap = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String headname = headerNames.nextElement();
            String headerValue = ((HttpServletRequest) request).getHeader(headname);
            headerMap.put(headname,headerValue);

        }

        log.debug("请求头信息为 headeMap={}",headerMap);

        //从请求体中获取信息

//        ServletInputStream inputStream = request.getInputStream();
//        BufferedReader reader = request.getReader();


        long start = System.currentTimeMillis();

        //放行当前请求
        chain.doFilter(request,response);
        long end = System.currentTimeMillis();

        log.debug("<====url ={},time={}",requestURI,(end-start));
    }

    @Override
    public void destroy() {
        log.debug("======================MyFilter销毁===================");
    }
}
